import axios, { type AxiosRequestHeaders, type AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import pinia from '@/stores/index';
import { useUserInfoStore } from '../stores/userInfo';

/* 定义response对象的data接口 */
interface ResponseData<T>{
	code:number,
	message:string,
	data:T,
	success:boolean
}

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL:import.meta.env.VITE_API_URL,
	timeout:5000
})

// 添加请求拦截器
service.interceptors.request.use(
	(config)=>{

		let token = useUserInfoStore().token;
  if (token) {
    (config.headers as AxiosRequestHeaders).token = token;
  }

		return config
	},
	(error)=>{
		return Promise.reject(error)
	}
)


// 添加响应拦截器
service.interceptors.response.use(
	async (response:AxiosResponse<ResponseData<any>>)=>{
		console.log(response);
		const result = response.data
		console.log(result);
		
		if(result.code !==20000 && result.code !==200 ){
			console.log("响应拦截器出了点问题");
			return Promise.reject(service.interceptors.response)
		}else{
			return result.data
		}
		
	},
	(error)=>{
		return Promise.reject(error)
	}
)


export default service